package com.carlinfo.stu_ques.demo.dao.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import com.carlinfo.stu_ques.common.dao.impl.BaseDaoImpl;
import com.carlinfo.stu_ques.common.util.FileUtil;
import com.carlinfo.stu_ques.demo.dao.IDynastyDao;
import com.carlinfo.stu_ques.demo.pojo.Dynasty;

/**
 * DAO的实现类
 * 
 * @author 90711
 *
 */
public class DynastyDaoImpl extends BaseDaoImpl<Dynasty> implements IDynastyDao {

	/**
	 * 文件路径
	 */
	private File resultFile = new File(this.parentFile,"dynasty.dat");

	/**
	 * 无参的构造函数，每次只要创建该对象，就会先执行
	 */
	@SuppressWarnings("unchecked")
	public DynastyDaoImpl() {
		this.readFile(resultFile);
	}

	@Override
	public int saveOneDao(Dynasty dynasty) {
		
		dynasty.setId(this.id);
		temId = dynasty.getId();
		super.saveOneDao(dynasty);
		this.writeFile(resultFile);
		return this.temId;
	}

	/**
	 * 更新一条记录
	 */
	@Override
	public void updateOneDao(Dynasty dynasty) {
		
		/**
		 * 获取其id将其覆盖
		 */
		this.temId = dynasty.getId();
		/* 调用父类的方法 */  
		super.updateOneDao(dynasty);
		this.writeFile(resultFile);
	}

	@Override
	public void deleteOneDao(Dynasty dynasty)
	{
		this.temId = dynasty.getId();
		super.deleteOneDao(dynasty);
		this.writeFile(resultFile);
	}

	@Override
	public boolean dbToFile(String path)
	{
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try
		{
			Map<Integer, Object> map = new TreeMap<Integer, Object>();
			List<Object> list = new ArrayList<Object>();
			File file = new File(path);
			FileOutputStream fos = new FileOutputStream(file+"\\dynasty.dat");
			FileUtil fileUtil = new FileUtil();
			/* 准备一条sql语句查询所有朝代 */
			String sql = "select * from dynasty;";
			conn = dbUtil.getConnection();
			pst = conn.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			rs = pst.executeQuery();
			int id = 0;
			/* 将数据库中的数据取出来 */
			while(rs.next())
			{
				Dynasty dynasty = new Dynasty();
				id = rs.getInt("id");
				dynasty.setId(id);
				dynasty.setAge(rs.getShort("age"));
				dynasty.setCapital(rs.getString("capital"));
				dynasty.setCreateTime(rs.getTimestamp("createTime"));
				dynasty.setSt(rs.getTimestamp("st"));
				dynasty.setName(rs.getString("name"));
				dynasty.setUpdateTime(rs.getTimestamp("updateTime"));
				/* 将数据按照id放入map中 */
				map.put(id, dynasty);
			}
			/* 将sql语句关闭 */
			pst.close();
			rs.close();
			/* 查询id最大值 */
			sql = "select max(id) from dynasty;";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			if(rs.next())
			{
				/* 将map和id最大值放入文件 */
				list.add(map);
				list.add(rs.getInt(1)+1);
				System.out.println("最大id："+rs.getInt(1));
			}
			fileUtil.writeObject(fos, list);
			return true;
		} catch (IOException e)
		{
			e.printStackTrace();
		} catch (SQLException e)
		{
			e.printStackTrace();
		} finally
		{
			/* 关闭链接 */
			dbUtil.closeAll(pst, conn, rs);
		}
		return false;
	}

	@Override
	public boolean fileToDb()
	{	
		List<Dynasty> list = this.selectListDao();
		if(list.size()!=0) {
			Connection conn = null;
			PreparedStatement pst = null;
			/* 每一次存之前,先将表清空 */
			String sql = "truncate table dynasty;";
			conn = dbUtil.getConnection();
			try
			{
				pst = conn.prepareStatement(sql);
				pst.executeUpdate();
				pst.close();
				sql = "INSERT INTO `dynasty`(`name`, `capital`, `age`, `st`, `createTime`, `updateTime`) VALUES (?, ?, ?, ?, ?, ?)";
				pst = conn.prepareStatement(sql);
				for (Dynasty dynasty : list)
				{
					pst.setObject(1,dynasty.getName());
					pst.setObject(2, dynasty.getCapital());
					pst.setObject(3, dynasty.getAge());
					pst.setObject(4, dynasty.getSt());
					pst.setObject(5, dynasty.getCreateTime());
					pst.setObject(6, dynasty.getUpdateTime());
					pst.addBatch();				
				}
				pst.executeBatch();
				pst.clearBatch();
				return true;
			} catch (SQLException e)
			{
				e.printStackTrace();
			} finally
			{
				dbUtil.closeAll(pst, conn, null);
			}
		} else
		{
			System.out.println("该文件是空的，没有数据可以插入");
		}
		return false;
	
	}

	
}
